var FeedParser = require('feedparser'),
    request = require('request'),
    error = require(_ROOT + '/app/errorLogger'),
    Promise = require('bluebird');

function readRss(url) {
  if (!url) error.log(new TypeError('Cannot readRss without a url'));

  var def = Promise.defer();

  var feeds = [];
  var req = request(url),
    feedparser = new FeedParser();

  req.on('error', function(err) {
    error.log('request url error:');
    error.log(err);
  });
  req.on('response', function(res) {
    var stream = this;

    if (res.statusCode != 200) return this.emit('error', new Error('Bad status code'));

    stream.pipe(feedparser);
  });

  feedparser.on('error', function(err) {
    error.log('FeedParser error:');
    error.log(err);
  });
  feedparser.on('readable', function() {
    // This is where the action is!
    var stream = this,
      meta = this.meta, // **NOTE** the "meta" is always available in the context of the feedparser instance
      item;

    while (item = stream.read()) {
      feeds.push(item);
    }
  });
  feedparser.on('end', function(err) {
    if (err) def.reject(err);

    def.resolve(feeds);
  });

  return def.promise;
}

module.exports = {
  read: readRss
};
